import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'dart:math';
import 'package:flutter/foundation.dart';

/// 2022年更新  适配 flutter 3.0
class IsolateBaseUsePage extends StatefulWidget {
  const IsolateBaseUsePage({super.key});

  @override
  State<StatefulWidget> createState() {
    return IsolateBaseUsePageState();
  }
}

class IsolateBaseUsePageState extends State
    with SingleTickerProviderStateMixin {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("isolate 基本使用 "),
      ),
      body: SizedBox.expand(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: const [Text("动画指示器示意: "), CupertinoActivityIndicator()],
            ),
            const SizedBox(
              height: 10,
            ),
            const Text("1亿随机数平均值测试"),
            Text(
              "计算结果: $result",
              style: Theme.of(context).textTheme.headline6,
            ),
            Text("计算总耗时: $cost ms"),
            const SizedBox(height: 33),
            Row(
              children: [
                TextButton(
                    onPressed: () {
                      _doTask();
                    },
                    child: const Text("普通执行")),
                const SizedBox(width: 33),
                TextButton(
                    onPressed: () {
                      _doTask2();
                    },
                    child: const Text("compute 执行")),
                const SizedBox(width: 33),
                TextButton(
                    onPressed: () {
                      _doTask3();
                    },
                    child: const Text("多个 isolate 执行"))
              ],
            )
          ],
        ),
      ),
    );
  }

  num result = 0;
  int cost = 0;
  int count = 10 * 10 * 1000 * 1000;

  void _doTask() {
    int sum = 0;
    int startTime = DateTime.now().millisecondsSinceEpoch;
    for (int i = 0; i < count; i++) {
      sum += Random().nextInt(10000);
    }
    int endTime = DateTime.now().millisecondsSinceEpoch;
    result = sum / count;
    cost = endTime - startTime;

    setState(() {});
  }

  void _doTask2() async {
    ///参数1 计算的耗时任务
    ///参数2
    ///参数3 任务的名称
    TaskResult taskResult = await compute<String, TaskResult>(
      _doTaskInCompute,
      'test01',
      debugLabel: "task1",
    );
    setState(
      () {
        result = taskResult.result;
        cost = taskResult.cost;
      },
    );
  }

  void _doTask3() async {
    ///参数1 计算的耗时任务
    ///参数2
    ///参数3 任务的名称
    Future<TaskResult> taskResult = compute<String, TaskResult>(
      _doTaskInCompute,
      'test03',
      debugLabel: "task2",
    );
    Future<TaskResult> taskResult2 = compute<String, TaskResult>(
      _doTaskInCompute,
      'test03',
      debugLabel: "task3",
    );
    List<TaskResult> taskResultList =
        await Future.wait([taskResult, taskResult2]);
    setState(
      () {
        result = taskResultList[0].result;
        cost = taskResultList[0].cost;
      },
    );
  }

  static Random random = Random();

  static Future<TaskResult> _doTaskInCompute(String arg) async {
    int count = 100000000;
    double result = 0;
    int cost = 0;
    int sum = 0;
    int startTime = DateTime.now().millisecondsSinceEpoch;
    for (int i = 0; i < count; i++) {
      sum += random.nextInt(10000);
      debugPrint("任务执行中$arg  $sum");
    }
    int endTime = DateTime.now().millisecondsSinceEpoch;
    result = sum / count;
    cost = endTime - startTime;
    debugPrint("任务执行完成 耗时 $cost");
    return TaskResult(
      result: result,
      cost: cost,
    );
  }
}

class TaskResult {
  final int cost;
  final double result;

  TaskResult({required this.cost, required this.result});
}
